package com.computergames.server.server.handler;

import com.computergames.server.message.QuitRoomRequestMessage;
import com.computergames.server.message.QuitRoomResponseMessage;
import com.computergames.server.server.session.RoomSessionFactory;
import com.computergames.server.server.session.RoomSessionService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;

@ChannelHandler.Sharable
public class QuitRoomRequestMessageHandler extends SimpleChannelInboundHandler<QuitRoomRequestMessage> {
    private static final AttributeKey<String> USER_ROOM_KEY = AttributeKey.valueOf("USER_ROOM");
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, QuitRoomRequestMessage msg) throws Exception {
        String roomName = (String)channelHandlerContext.attr(AttributeKey.valueOf("USER_ROOM")).get();
        String username = msg.getUsername();
        RoomSessionService roomSessionService = RoomSessionFactory.getRoomSession();
        Boolean isSuccess = roomSessionService.removeMember(roomName, username);
        if (isSuccess) {
            // 使房间名与通道解绑
            channelHandlerContext.channel().attr(USER_ROOM_KEY).set(null);
            channelHandlerContext.writeAndFlush(new QuitRoomResponseMessage(true, "退出房间成功"));
        } else {
            channelHandlerContext.writeAndFlush(new QuitRoomResponseMessage(false, "退出房间失败"));
        }
    }
}
